package cn.jingyinghui.generic;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Safelist;
import org.owasp.html.HtmlPolicyBuilder;
import org.owasp.html.PolicyFactory;

public class HtmlSanitizerService {

    // 组合清洗策略
    public String sanitizeAndExtractText(String html) {
        // 1. Jsoup基础清洗
        String jsoupCleaned = jsoupSanitize(html);

        // 2. OWASP深度清洗
        String owaspCleaned = owaspSanitize(jsoupCleaned);

        // 3. 转换为纯文本并优化
        return htmlToPlainText(owaspCleaned);
    }

    private String jsoupSanitize(String html) {
        Safelist safelist = Safelist.relaxed()
                .addAttributes("img", "width", "height", "alt") // 允许图片尺寸属性
                .preserveRelativeLinks(false) // 不保留相对链接
                .removeProtocols("a", "href", "javascript"); // 禁用javascript协议

        return Jsoup.clean(html, safelist);
    }

    private String owaspSanitize(String html) {
        PolicyFactory policy = new HtmlPolicyBuilder()
                .allowElements("h1", "h2", "h3", "p", "ul", "ol", "li", "b", "strong", "i", "em", "br", "img")
                .allowAttributes("src", "alt", "width", "height").onElements("img")
                .allowTextIn("script", "style") // 禁止执行但允许文本内容
                .toFactory();

        return policy.sanitize(html);
    }

    public String htmlToPlainText(String html) {
        // 1. 使用Jsoup解析为文档
        Document doc = Jsoup.parse(html);

        // 2. 提取纯文本
        String text = doc.text();

        // 3. 优化文本格式
        return text.replaceAll("\\s+", " ")  // 合并连续空格
                .replaceAll("\\p{C}", "") // 移除控制字符
                .trim();
    }
}